/**
 * Wire管理器 - 专门管理Wire连接组件
 * 与CanvasManager分离，只负责Wire的生命周期和渲染
 */
import { IWire, ConnectionStyle, IPin, HitTestResult, HitType, Wire } from '../circuit-elements.js';
import { globalMgr } from '../globalMgr.js';

export class WireManager {
  private wires: Map<string, IWire> = new Map();
  private canvasContainer: SVGGElement | null = null;
  private wireLayer: SVGGElement | null = null; // Wire专用渲染层
  
  constructor() {}
  
  /**
   * 设置画布容器
   */
  setCanvasContainer(canvasContainer: SVGGElement): void {
    this.canvasContainer = canvasContainer;
    
    // 创建Wire专用渲染层
    this.wireLayer = document.createElementNS('http://www.w3.org/2000/svg', 'g');
    this.wireLayer.setAttribute('id', 'wire-layer');
    this.wireLayer.setAttribute('class', 'wire-layer');
    this.canvasContainer.appendChild(this.wireLayer);
  }
  
  /**
   * 添加Wire
   */
  addWire(wire: IWire): void {
    this.wires.set(wire.id, wire);
    
    // 渲染Wire到专用层
    this.renderWire(wire);
    
    // 注册到全局管理器
    globalMgr.registerWire(wire);
  }
  
  /**
   * 移除Wire
   */
  removeWire(wireId: string): void {
    const wire = this.wires.get(wireId);
    if (wire) {
      // 从DOM移除
      const wireElement = this.wireLayer?.querySelector(`[data-wire-id="${wireId}"]`);
      if (wireElement) {
        wireElement.remove();
      }
      
      // 从管理器移除
      this.wires.delete(wireId);
      
      // 从全局管理器注销
      globalMgr.unregisterWire(wireId);
    }
  }
  
  /**
   * 创建Wire连接两个Pin
   */
  createWireBetweenPins(startPinId: string, endPinId: string, style: ConnectionStyle = ConnectionStyle.Straight): IWire | null {
    // 验证连接
    const startPin = globalMgr.getPinById(startPinId);
    const endPin = globalMgr.getPinById(endPinId);
    
    if (!startPin || !endPin) {
      console.error('Cannot create wire: pins not found');
      return null;
    }
    
    if (startPin.componentId === endPin.componentId) {
      console.error('Cannot create wire: pins belong to same component');
      return null;
    }
    
    // 检查是否已经存在连接
    if (this.wireExistsBetweenPins(startPinId, endPinId)) {
      console.warn('Wire already exists between these pins');
      return null;
    }
    
    // 创建新的Wire
    const wireId = `wire_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
    const wire = new Wire({
      id: wireId,
      startPinId,
      endPinId,
      style
    });
    
    // 建立Pin之间的连接关系
    this.connectPins(startPin, endPin);
    
    // 添加Wire
    this.addWire(wire);
    
    console.log(`Created wire ${wireId} between ${startPinId} and ${endPinId}`);
    return wire;
  }
  
  /**
   * 重新渲染所有Wire
   */
  renderAllWires(): void {
    if (!this.wireLayer) return;
    
    // 清空当前层
    this.wireLayer.innerHTML = '';
    
    // 重新渲染所有Wire
    for (const wire of this.wires.values()) {
      this.renderWire(wire);
    }
  }
  
  /**
   * 渲染单个Wire
   */
  renderWire(wire: IWire): void {
    if (!this.wireLayer) return;
    
    const wireElement = this.wireLayer.querySelector(`[data-wire-id="${wire.id}"]`);
    
    // 获取Pin世界坐标的方法
    const getPinWorldPosition = (pinId: string) => {
      const pin = globalMgr.getPinById(pinId);
      if (!pin) return null;
      
      const element = globalMgr.getElementById(pin.componentId);
      if (!element) return null;
      
      const pinLocalPos = element.getPinPosition(pin);
      return {
        x: element.position.x + pinLocalPos.x,
        y: element.position.y + pinLocalPos.y
      };
    };
    
    const svg = wire.render(getPinWorldPosition);
    
    if (wireElement) {
      // 更新现有Wire
      wireElement.outerHTML = svg;
    } else {
      // 添加新Wire
      this.wireLayer.insertAdjacentHTML('beforeend', svg);
    }
  }
  
  /**
   * 获取指定位置的Wire
   */
  getWireAtPosition(point: { x: number; y: number }, tolerance: number = 10): IWire | null {
    const getPinWorldPosition = (pinId: string) => {
      const pin = globalMgr.getPinById(pinId);
      if (!pin) return null;
      
      const element = globalMgr.getElementById(pin.componentId);
      if (!element) return null;
      
      const pinLocalPos = element.getPinPosition(pin);
      return {
        x: element.position.x + pinLocalPos.x,
        y: element.position.y + pinLocalPos.y
      };
    };
    
    for (const wire of this.wires.values()) {
      const hitResult = (wire as any).hitTestWithPinPositions ? 
        (wire as any).hitTestWithPinPositions(point, getPinWorldPosition, tolerance) :
        wire.hitTest(point, tolerance);
      if (hitResult && hitResult.isHit) {
        return wire;
      }
    }
    
    return null;
  }
  
  /**
   * 获取所有Wire
   */
  getAllWires(): IWire[] {
    return Array.from(this.wires.values());
  }
  
  /**
   * 根据ID获取Wire
   */
  getWireById(wireId: string): IWire | undefined {
    return this.wires.get(wireId);
  }
  
  /**
   * 设置连接样式
   */
  setConnectionStyle(style: ConnectionStyle): void {
    for (const wire of this.wires.values()) {
      wire.style = style;
    }
    this.renderAllWires();
  }
  
  /**
   * 检查两个Pin之间是否已经存在Wire
   */
  private wireExistsBetweenPins(pinId1: string, pinId2: string): boolean {
    for (const wire of this.wires.values()) {
      if ((wire.startPinId === pinId1 && wire.endPinId === pinId2) ||
          (wire.startPinId === pinId2 && wire.endPinId === pinId1)) {
        return true;
      }
    }
    return false;
  }
  
  /**
   * 连接两个Pin
   */
  private connectPins(pin1: IPin, pin2: IPin): void {
    // 建立双向连接
    if (!pin1.connectedPins.includes(pin2)) {
      pin1.connectedPins.push(pin2);
    }
    if (!pin2.connectedPins.includes(pin1)) {
      pin2.connectedPins.push(pin1);
    }
    
    // 网络管理由GlobalManager的registerWire方法处理
  }
}

